﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KPIS.GERP.Models;
using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.WEB.GIMS.Class;
using KPIS.GERP.WEB.GIMS.MasResourceService;
using Resources;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    public class MasResourceItemUtil
    {
        public static string CheckCodeDuplicate(int resItemId, string code, Controller ct)
        {
            using (var db = new GERPContext())
            {
                var mri =
                    db.MasResourceItems.Include("MasResourceSubGroup.MasResourceGroup")
                        .Where(o => o.RecordStatus != "D" &&
                                    o.ResItemId != resItemId && o.Code == code);
                if (mri.Any())
                {
                    string rul = ct.Url.Action("Details", "MasResourceItem") + "/?id=";
                    string errrorStr = "ขออภัย มีวัสดุรายการซ้ำ <br/>" +
                                       string.Join("<br/>\n",
                                           mri.ToList().Select(o =>

                                               "<a target='_blank' href='" +
                                               rul + o.ResItemId +
                                               "'>" +
                                               o.MasResourceSubGroup.MasResourceGroup.Name + "/" +
                                               o.MasResourceSubGroup.Name + "/" +
                                               o.Code + " - " + o.Name + "</a>"));


                    return errrorStr;
                }
            }
            return null;
        }

        public static string GenerateNewCode(int resSubGrpId)
        {
            string maxCode = "";
            using (var db = new GERPContext())
            {
                MasResourceSubGroup subGrpCode = db.MasResourceSubGroups.First(o => o.ResSubGrpId == resSubGrpId);
                var r1 = db.MasResourceItems.Include("MasResourceSubGroup").ToList()
                    .Where(o =>
                        o.ResSubGrpId != null &&
                        o.RecordStatus != "D" &&
                        o.Code != null && 
                        o.Code.Split(new[] { "-" }, StringSplitOptions.None).Count() > 1 &&
                        o.Code.StartsWith(subGrpCode.Code)
                    ).Select(o => new
                    {
                        ResItemId = o.ResItemId,
                        ResSubGrpId = o.ResSubGrpId,
                        Code = o.Code,
                        CodeInt = ConvertUtility.ConvertOrDefaultStringToInt(
                            o.Code.Split(new[] { "-" }, StringSplitOptions.None)[
                                o.Code.Split(new[] { "-" }, StringSplitOptions.None).Length - 1]
                                .Replace(" ", ""))
                    }).OrderByDescending(o=>o.CodeInt);
                int maxCodeInt = r1.Max(o => o.CodeInt) ;
                string codeToCheck;
                do
                {
                    codeToCheck = subGrpCode.Code + "-" + (++maxCodeInt).ToString("00000");
                } while (db.MasResourceItems.Any(o => o.Code == codeToCheck));
                return codeToCheck;
            }
        }
    }

    public class MasResourceItemController : Controller
    {
        MasResourceServiceClient s = new MasResourceServiceClient();

        #region resource item

        public JsonResult GenerateNewCodeJs(int resSubGrpId)
        {
            string newResItemCode = MasResourceItemUtil.GenerateNewCode(resSubGrpId);
            return Json(new{NewResItemCode = newResItemCode}, JsonRequestBehavior.AllowGet);
        }
        public JsonResult CheckCodeDuplicateJs(int resItemId, string code)
        {
            string errorStr = MasResourceItemUtil.CheckCodeDuplicate(resItemId, code, this);
            return Json(new
            {
                Success = string.IsNullOrWhiteSpace(errorStr)?1:0, 
                ErrorStr = errorStr }, JsonRequestBehavior.AllowGet); 
        }
        public ActionResult Index(int resSubGrpId)
        {
            // Resource item 
            var model = s.SelectResourceItem(new MasResourceItem{RecordStatus = "!D", ResSubGrpId = resSubGrpId}, null);
            ViewBag.resSubGrpId = resSubGrpId;

            return View(model); 
        }

		public ActionResult Details(int id)
		{
			var model = s.SelectResourceItem(new MasResourceItem {ResItemId = id}, null).FirstOrDefault();
            if(model == null) return new HttpNotFoundResult("ไม่พบข้อมูล");
		    int resSubGrpId = model.ResSubGrpId.Value;
            ViewBag.resSubGrpId = resSubGrpId;

			return View(model);
		}

		public ActionResult Create(int resSubGrpId)
		{
		    var model = new MasResourceItem();
		    model.ResSubGrpId = resSubGrpId;
		    model.StdPrice = 0;
		    model.MinPrice = 0;
		    model.MaxPrice = 0;
		    model.MinQty = 0;
		    model.MaxQty = 0;
            ViewBag.resSubGrpId = resSubGrpId;

			return View(model);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult Create(int resSubGrpId, MasResourceItem model, HttpPostedFileBase fileForImageName)
		{
		    model = VarifyModel(model);
		    
            string fileExtension = "";
            if(fileForImageName != null && fileForImageName.ContentLength > 0)
            {
                fileExtension = Path.GetExtension(fileForImageName.FileName);
                if (!FileType(fileExtension)) ModelState.AddModelError("ImageName", "รองรับไฟล์ .jpg, png, gif เท่านั้น");
            }
			if (ModelState.IsValid)
			{
				var id = s.InsertResourceItem(model, GimsMembership.CurrentEmpId);
                
                // file
                // 1 upload new file
                if(fileForImageName != null && fileForImageName.ContentLength > 0)
                {
                    model.ResItemId = id;
                    string folder_path = Server.MapPath(masResourceItemPath);
                    DirectoryInfo di = new DirectoryInfo(folder_path);
                    if (!di.Exists)
                    {
                        Directory.CreateDirectory(folder_path);
                        Models.Class.FileUtility.FolderACL("Everyone", folder_path);
                    }

                    model.ImageName = model.ResItemId + fileExtension;
                    string filePath = Path.Combine(folder_path, model.ImageName);

                    fileForImageName.SaveAs(filePath);

				    s.UpdateResourceItem(model, GimsMembership.CurrentEmpId);
                }

				return RedirectToAction("Details", new {id, resSubGrpId});
			}

            ViewBag.resSubGrpId = resSubGrpId;

			return View(model);
		}

		public ActionResult Edit(int resSubGrpId, int id)
		{
			var model = s.SelectResourceItem(new MasResourceItem {ResItemId = id}, null).FirstOrDefault();
            ViewBag.resSubGrpId = resSubGrpId;

			return View(model);
		}

        private string masResourceItemPath = "~/App_Data/uploads/masresourceitem";
		[HttpPost, ValidateAntiForgeryToken]
		public ActionResult Edit(int resSubGrpId, int id, MasResourceItem model, HttpPostedFileBase fileForImageName, string chbDeleteImage)
		{
		    model = VarifyModel(model);

		    string fileExtension = "";
            if(fileForImageName != null && fileForImageName.ContentLength > 0)
            {
                fileExtension = Path.GetExtension(fileForImageName.FileName);
                if (!FileType(fileExtension)) ModelState.AddModelError("ImageName", "รองรับไฟล์ .jpg, png, gif เท่านั้น");
            }
		    if (ModelState.IsValid)
			{
                // file
                // 1 upload new file
                if(fileForImageName != null && fileForImageName.ContentLength > 0)
                {
                    string folder_path = Server.MapPath(masResourceItemPath);
                    DirectoryInfo di = new DirectoryInfo(folder_path);
                    if (!di.Exists)
                    {
                        Directory.CreateDirectory(folder_path);
                        Models.Class.FileUtility.FolderACL("Everyone", folder_path);
                    }

                    model.ImageName = model.ResItemId + fileExtension;
                    string filePath = Path.Combine(folder_path, model.ImageName);

                    fileForImageName.SaveAs(filePath);
                }
                // 2 remove file
                if(chbDeleteImage == "Yes")
                {
                    model.ImageName = null;
                }

				s.UpdateResourceItem(model, GimsMembership.CurrentEmpId);
				return RedirectToAction("Details", new {id, resSubGrpId});
			}

            ViewBag.resSubGrpId = resSubGrpId;

			return View(model);
		}

        public ActionResult Image(int id)
        {
			var model = s.SelectResourceItem(new MasResourceItem {ResItemId = id}, null).FirstOrDefault();
            if(model == null) return new HttpNotFoundResult("ไม่พบข้อมูล");
		    int resSubGrpId = model.ResSubGrpId.Value;
            ViewBag.resSubGrpId = resSubGrpId;

            return View(model);
        }

        public FileStreamResult StreamFileFromDisk4(string imageName)
        {
            string dirPath = Server.MapPath(masResourceItemPath);
            dirPath = dirPath.Replace("\\", "/").EndsWith("/") ? dirPath : dirPath + "/";
            string path = dirPath + imageName;
            string fileExt = Path.GetExtension(path);
            if(System.IO.File.Exists(path))
                return File(new FileStream(path, FileMode.Open), fileExt, imageName);
            return null;
        }

        public bool FileType(String file_extentions)
        {
            bool ret = false;

            if (file_extentions.ToLower().StartsWith(".jpg"))
                ret = true;
            else if (file_extentions.ToLower().StartsWith(".png"))
                ret = true;
            else if (file_extentions.ToLower().StartsWith(".gif"))
                ret = true;
            else if (file_extentions.ToLower().StartsWith(".bmp"))
                ret = true;
            else
                ret = false;
            return ret;
        }

        public ActionResult Delete(int resSubGrpId, int id)
		{
		    s.DeleteResourceItem(id, GimsMembership.CurrentEmpId);

		    return RedirectToAction("Index", new {resSubGrpId});
		}


        [HttpPost, ValidateAntiForgeryToken]
		public ActionResult DeleteAll(int[] deleteIds)
		{
			if (deleteIds == null)
				return Json(new { success = true });

			try
			{
				foreach (int delete in deleteIds)
				{
					s.DeleteResourceItem(delete, GimsMembership.CurrentEmpId);
				}

				ModelState.AddModelError(ErrorLocalization.Error, string.Format("ลบข้อมูลไปทั้งหมด {0} รายการ", deleteIds.Length.ToString("#,##0")));
				return Json(new {success = true});
			}
			catch (Exception ex)
			{
				ModelState.AddModelError(ErrorLocalization.Error, ErrorLocalization.ErrorWhileDeleteData);
				Models.Class.GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
				return Json(new {success = false});
			}
		}
        
        private MasResourceItem VarifyModel(MasResourceItem model)
        {
            if (string.IsNullOrWhiteSpace(model.Name))
            {
                ModelState.AddModelError("Name", "กรุณากรอกชื่อรายการพัดสุ");
            }

            if(model.ResSubGrpId == 0 || model.ResSubGrpId == null || s.SelectResourceSubGroup(new MasResourceSubGroup {ResSubGrpId = model.ResSubGrpId.Value, RecordStatus = "!D"}, null).FirstOrDefault() == null)
            {
                ModelState.AddModelError("ResSubGrpId", "ไม่มีข้อมูลกลุ่มพัสดุ");
            }

            if (string.IsNullOrWhiteSpace(model.Code))
            {
                ModelState.AddModelError("Code", "กรุณากรอกรหัส");
            }

            using (var db = new GERPContext())
            {
                var mri = db.MasResourceItems.Where(o => o.RecordStatus != "D" &&
                                                         o.ResItemId != model.ResItemId && o.Code == model.Code);
                if (mri.Any())
                {
                    var mri1 = mri.First();
                    ModelState.AddModelError("Code",
                        "ขออภัย มีวัสดุรายการซ้ำ (" + (mri1.Name.Replace("'", "").Replace("\"", "") + ")"));
                }
            }

            return model;
        }

        #endregion

    }
}
